package com.example.blog.ws;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.blog.util.UserUtils.UserUtils;
import com.example.blog.util.Web.WebTest;
import com.example.blog.ws.service.ChatMassageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/websocket/{userId}")
@Component
@Slf4j
public class ChatEndpointService {

    private static UserUtils utils;
    private static ChatMassageService chatMassageService;

    @Resource
    public void setUserService(ChatMassageService chatMassageService) {
        ChatEndpointService.chatMassageService = chatMassageService;
    }

    @Resource
    public void getUserName(UserUtils utils) {
        ChatEndpointService.utils = utils;
    }

    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    private static final ConcurrentHashMap<String, ChatEndpointService> webSocketMap = new ConcurrentHashMap<>();
    private Session session;
    private String userId;

    public String getName() {
        return utils.getName(Integer.valueOf(userId));
    }

    public String getHeader() {
        return utils.getUrl(Integer.valueOf(userId));
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        String name = getName();
        webSocketMap.put(userId, this);
        addOnlineCount();
        int onlineCount1 = getOnlineCount();
        chatMassageService.saveOnlineCount(String.valueOf(onlineCount1));
        log.info("用户{}连接成功,当前在线人数为{}", name, getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("IO异常", e);
        }
    }

    @OnClose
    public void onClose() {
        String name = getName();
        webSocketMap.remove(userId);
        subOnlineCount();
        int onlineCount1 = getOnlineCount();
        chatMassageService.saveOnlineCount(String.valueOf(onlineCount1));
        log.info("用户{}关闭连接！当前在线人数为{}", name, getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        CompletableFuture.runAsync(() -> {
            try {
                String neckName = getName();
                String header = getHeader();
                log.info("收到消息：{}", message);

                // 这里应该解析接收到的JSON消息
                JSONObject jsonMessage = JSON.parseObject(message);
                String content = jsonMessage.getString("content");
                String replaceWebsiteTitles = WebTest.replaceWebsiteTitles(content);
                String receiveUserId = jsonMessage.getString("receiveUserId");
                String messageType = jsonMessage.getString("messageType");
                String headerUrl = jsonMessage.getString("headerUrl");
                String name = jsonMessage.getString("name");

                // 创建消息对象
                JSONObject msg = new JSONObject();
                msg.put("content", replaceWebsiteTitles);
                msg.put("receiveUserId", receiveUserId);
                msg.put("messageType", messageType);
                msg.put("headerUrl", headerUrl);
                msg.put("name", name);

                if ("group".equals(messageType)) {
                    for (String item : webSocketMap.keySet()) {
                        try {
                            chatMassageService.saveGroupMessage(userId, neckName, header, replaceWebsiteTitles, messageType);
                            webSocketMap.get(item).sendMessage(msg.toJSONString());
                        } catch (IOException e) {
                            log.error("消息发送异常", e);
                        }
                    }
                } else if ("single".equals(messageType)) {
                    if (webSocketMap.containsKey(receiveUserId)) {
                        chatMassageService.saveSingleMessage(userId, receiveUserId, neckName, header, replaceWebsiteTitles, messageType);
                        sendUserInfo(receiveUserId, msg.toJSONString());
                    } else {
                        chatMassageService.saveSingleMessage(userId, receiveUserId, neckName, header, replaceWebsiteTitles, messageType);
                    }
                }
            } catch (Exception e) {
                log.error("消息处理异常", e);
            }
        });
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage(), error);
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static void sendUserInfo(String receiveUserId, String message) throws IOException {
        if (webSocketMap.containsKey(receiveUserId)) {
            webSocketMap.get(receiveUserId).sendMessage(message);
        } else {
            log.error("用户{}不在线", receiveUserId);
        }
    }

    // 获取所有在线用户的ID
    public static Set<String> getAllOnlineUserIds() {
        return webSocketMap.keySet();
    }

    public static int getOnlineCount() {
        return onlineCount.get();
    }

    public static void addOnlineCount() {
        onlineCount.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineCount.decrementAndGet();
    }
}



